package com.monitoring.interfaces.controller;

import com.monitoring.application.dto.SensorDTO;
import com.monitoring.application.service.SensorApplicationService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/sensors")
public class SensorController {
    private final SensorApplicationService sensorService;
    
    public SensorController(SensorApplicationService sensorService) {
        this.sensorService = sensorService;
    }
    
    // 创建传感器
    @PostMapping
    public ResponseEntity<SensorDTO> createSensor(@RequestBody SensorDTO sensorDTO) {
        SensorDTO createdSensor = sensorService.createSensor(sensorDTO);
        return ResponseEntity.ok(createdSensor);
    }
    
    // 根据ID获取传感器
    @GetMapping("/{id}")
    public ResponseEntity<SensorDTO> getSensorById(@PathVariable Long id) {
        return sensorService.getSensorById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    // 获取所有传感器
    @GetMapping
    public ResponseEntity<List<SensorDTO>> getAllSensors() {
        List<SensorDTO> sensors = sensorService.getAllSensors();
        return ResponseEntity.ok(sensors);
    }
    
    // 根据位置获取传感器
    @GetMapping("/location/{location}")
    public ResponseEntity<List<SensorDTO>> getSensorsByLocation(@PathVariable String location) {
        List<SensorDTO> sensors = sensorService.getSensorsByLocation(location);
        return ResponseEntity.ok(sensors);
    }
    
    // 获取活跃的传感器
    @GetMapping("/active")
    public ResponseEntity<List<SensorDTO>> getActiveSensors() {
        List<SensorDTO> sensors = sensorService.getActiveSensors();
        return ResponseEntity.ok(sensors);
    }
    
    // 更新传感器读数
    @PutMapping("/{id}/reading")
    public ResponseEntity<Void> updateSensorReading(
            @PathVariable Long id,
            @RequestParam double temperature,
            @RequestParam double humidity) {
        sensorService.updateSensorReading(id, temperature, humidity);
        return ResponseEntity.ok().build();
    }
    
    // 激活传感器
    @PutMapping("/{id}/activate")
    public ResponseEntity<SensorDTO> activateSensor(@PathVariable Long id) {
        SensorDTO sensor = sensorService.activateSensor(id);
        return ResponseEntity.ok(sensor);
    }
    
    // 停用传感器
    @PutMapping("/{id}/deactivate")
    public ResponseEntity<SensorDTO> deactivateSensor(@PathVariable Long id) {
        SensorDTO sensor = sensorService.deactivateSensor(id);
        return ResponseEntity.ok(sensor);
    }
    
    // 删除传感器
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSensor(@PathVariable Long id) {
        sensorService.deleteSensor(id);
        return ResponseEntity.ok().build();
    }
}